package com.mrs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mrs.common.ResponseResult;
import com.mrs.common.constants.SystemConstants;
import com.mrs.common.vo.ArticleDetailVo;
import com.mrs.common.vo.ArticleListVo;
import com.mrs.common.vo.HotArticleVo;
import com.mrs.common.vo.PageVo;
import com.mrs.dto.ArticleDto;
import com.mrs.entity.Article;
import com.mrs.entity.ArticleTag;
import com.mrs.entity.Category;
import com.mrs.mapper.ArticleMapper;
import com.mrs.service.ArticleService;
import com.mrs.service.ArticleTagService;
import com.mrs.service.CategoryService;
import com.mrs.utils.BeanCopyUtils;
import com.mrs.utils.RedisCache;
import org.junit.jupiter.params.shadow.com.univocity.parsers.annotations.Copy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * description: ArticleServiceImpl
 * date: 2022/8/5 22:30
 * author: MR.孙
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper,Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleTagService articleTagService;

    /**
     * @description: 查询热门文章，封装成ResponseResult返回
     * @return: com.mrs.common.ResponseResult
     * @author: MR.孙
     * @date: 2022/8/6 8:53
    */
    public ResponseResult hotArticleList() {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<Article>();
        //1. 必须是正式文章(不是草稿)
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);

        //2. 按照浏览量降序排序
        queryWrapper.orderByDesc(Article::getViewCount);

        //3. 热门文章最多为10条(分页实现)
        Page<Article> page = new Page(1, 10);
        page(page,queryWrapper);
        //Records就是数据库查询的数据
        List<Article> articles = page.getRecords();

        //由于不需要返回那么多字段,所以这里用vo进行优化返回
      /*  List<HotArticleVo> articleVos = new ArrayList<>();
        for (Article article : articles) {
            HotArticleVo vo = new HotArticleVo();
            //Bean拷贝
            BeanUtils.copyProperties(article,vo);
            articleVos.add(vo);
        }*/
        List<HotArticleVo> articleVos = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);
        return ResponseResult.okResult(articleVos);
    }


    /**
     * @description:  查询文章列表
     * @param pageNum
     * @param pageSize
     * @param categoryId
     * @return: com.mrs.common.ResponseResult
     * @author: MR.孙
     * @date: 2022/8/6 23:16
    */
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();
        //1.是否传参categoryId
        queryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0,
                Article::getCategoryId,categoryId);
        //2.文章是否为正常发布状态
        queryWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        //3.置顶文章排序(isTop降序)
        queryWrapper.orderByDesc(Article::getIsTop);

        //分页查询
        Page<Article> page = new Page<>(pageNum,pageSize);
        page(page,queryWrapper);

        //获取分页查询到的文章信息
        List<Article> articles = page.getRecords();

        //根据查询categoryId查询查询categoryName
        // for (Article article : articles) {
        //     Category category = categoryService.getById(article.getCategoryId());
        //     article.setCategoryName(category.getName());
        // }

        //查询categoryName
        articles.stream()
                .map(article ->
                        //查询分类id,查询分类信息,获取分类名称
                        //把分类名称设置给article
                        article.setCategoryName(categoryService
                                .getById(article.getCategoryId())
                                .getName())).collect(Collectors.toList());


        //封装VO 返回查询结果
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(),
                ArticleListVo.class);

        PageVo pageVo = new PageVo(articleListVos,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }


    /**
     * @description:  查询文章详情
     * @param id
     * @return: com.mrs.common.ResponseResult
     * @author: MR.孙
     * @date: 2022/8/7 17:02
    */
    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);
        //从redis中获取viewCount
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        article.setViewCount(viewCount.longValue());

        //封装成VO
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);

        //根据分类id查询分类名
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);

        if(category != null){
            articleDetailVo.setCategoryName(category.getName());
        }

        //封装响应返回
        return ResponseResult.okResult(articleDetailVo);
    }

    /**
     * @description:  当更新浏览量时去更新redis数据
     * @param id
     * @return: com.mrs.common.ResponseResult
     * @author: MR.孙
     * @date: 2022/8/13 12:25
    */
    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应 id的浏览量
        redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);
        return ResponseResult.okResult();
    }


    /**
     * @description:  新增文章
     * @param articleDto
     * @return: com.mrs.common.ResponseResult
     * @author: MR.孙
     * @date: 2022/9/12 9:28
    */
    @Override
    @Transactional
    public ResponseResult addArticle(ArticleDto articleDto) {
        //1. 添加文章到文章表
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        save(article);

        //2.1 从ArticleDto拿到前端传过来的tag_id集合tags
        //2.2 添加新增文章后的文章id和前端传过来的tag_id集合tags的关联
        List<ArticleTag> articleTagList = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());

        //添加文章与标签表之间的关联关系到article_tag表
        articleTagService.saveBatch(articleTagList);

        return ResponseResult.okResult();
    }
}
